package com.haha.gulimall.product.exception;

import com.haha.common.exception.BizCodeEnum;
import com.haha.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.haha.gulimall.product.controller")
@Slf4j
public class GulimallExceptionControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleDataValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
            System.out.println("have a error");
            Map<String, String> errorMap = new HashMap<>();
            result.getFieldErrors().forEach(a -> {
                String message = a.getDefaultMessage();
                String field = a.getField();
                errorMap.put(field, message);
            });
        //log.error("异常{},type:{}",e.getMessage(),e.getClass());
//        return R.error(400, e.getMessage());
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",errorMap);

    }


    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable e) {
        log.error("find error",e);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }
}
